<template>
    <div class="medical-records-list-container">
        <global-search @submitSearch="submitSearch" class="global-tool-search" :showCoder="showCoder" :showDoctor="showDoctor">
            <template slot="other-form">
                <el-form-item label="检索">
                    <el-input v-model="searchForm.keyword" class="keyword-input" size="small"
                              placeholder="请输入病案号/患者姓名"></el-input>
                </el-form-item>
                <el-form-item label="缺陷类型" v-if="!errReason">
                    <el-select class="defectSate-input" size="small" v-model="searchForm.defectSate" placeholder="">
                        <el-option-group label="">
                            <el-option :value="0" label="全部"></el-option>
                            <el-option :value="8" label="有主要诊断缺陷"></el-option>
                            <el-option :value="10" label="有主要手术操作缺陷"></el-option>
                        </el-option-group>
                        <el-option-group label="">
                            <el-option :value="7" label="有诊断编码缺陷"></el-option>
                            <el-option :value="9" label="有手术操作编码缺陷"></el-option>
                            <el-option :value="11" label="有门(急)诊诊断编码缺陷"></el-option>
                            <el-option :value="12" label="有损伤中毒外因编码缺陷"></el-option>
                            <el-option :value="13" label="有病理诊断编码缺陷"></el-option>
                        </el-option-group>
                        <el-option-group label="">
                            <el-option :value="5" label="有编码缺陷"></el-option>
                            <el-option :value="6" label="有非编码缺陷"></el-option>
                        </el-option-group>
                        <el-option-group label="">
                            <el-option :value="4" label="有缺陷"></el-option>
                            <el-option :value="3" label="无缺陷"></el-option>
                        </el-option-group>
                        <el-option-group label="">
                            <el-option :value="1" label="有扣分"></el-option>
                            <el-option :value="2" label="无扣分"></el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="审核状态">
                    <el-select class="status-input" size="small" v-model="searchForm.checkState" placeholder="">
                        <el-option label="全部" :value="null"></el-option>
                        <el-option label="已审核" :value="1"></el-option>
                        <el-option label="驳回" :value="2"></el-option>
                        <el-option label="未审核" :value="0"></el-option>
                    </el-select>
                </el-form-item>
            </template>
        </global-search>
        <div class="table-box">
            <div class="head">
                <h3>病案首页列表<span v-if="errReason">({{errReason}})</span></h3>
                <div class="btn-box">
                    <el-button type="primary" icon="el-icon-upload2" size="small" v-auth="{code: 100003000004}"
                               @click="toExportList">列表导出
                    </el-button>
                    <el-button type="primary" icon="el-icon-upload2" size="small" v-auth="{code: 100003000004}"
                               @click="toExportWT4">卫统4标准导出
                    </el-button>
                    <el-button type="primary" icon="el-icon-upload2" size="small" v-auth="{code: 100003000004}"
                               @click="toExportHQMS">HQMS标准导出
                    </el-button>
                    <el-button type="primary" icon="el-icon-upload2" size="small" v-auth="{code: 100003000004}"
                               @click="toExportSJJX">三级医院绩效标准导出
                    </el-button>
                </div>
            </div>
            <el-table
                ref="tableData"
                :data="tableData"
                row-key="id"
                tooltip-effect="light"
                border
                :max-height="tableHeight"
                class="data-table"
                @sort-change="sortChange"
                @selection-change="handleSelectionChange">
                <el-table-column
                    type="selection"
                    :reserve-selection="true"
                    align="center"
                    width="30">
                </el-table-column>
                <el-table-column
                    label="序号"
                    type="index"
                    align="center"
                    width="40">
                </el-table-column>
                <el-table-column
                    prop="orgName"
                    label="机构名称"
                    min-width="140"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="medicalRecordSign"
                    label="病案号"
                    align="center"
                    min-width="90"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span class="to-child-page" :class="viewInfoMonth(scope.row.dischargeDate) ? '' : 'disabled'"
                              @click="toInfo(scope.row, scope.$index)">{{scope.row.medicalRecordSign}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="hospitalTime"
                    label="住院次数"
                    align="center"
                    min-width="80"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="patientName"
                    label="患者姓名"
                    align="center"
                    min-width="65"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="departmentName"
                    label="出院科室"
                    min-width="110"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="dischargeDate"
                    label="出院日期"
                    align="center"
                    min-width="85"
                    sortable="custom"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row.dischargeDate.substring(0, 10)}}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="resident"
                    label="住院医师"
                    align="center"
                    min-width="80"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="coder"
                    label="编码员"
                    align="center"
                    min-width="80"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="diagnosis"
                    label="主要诊断"
                    min-width="120"
                    sortable="custom"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row.diagnosis}}<br>
                        {{scope.row.diagnosisCode}}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="surgery"
                    label="主要手术"
                    min-width="120"
                    sortable="custom"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row.surgery}}<br>
                        {{scope.row.surgeryCode}}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="codingTipCount"
                    label="编码项缺陷"
                    align="center"
                    min-width="100"
                    sortable="custom"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-tooltip v-if="scope.row.codingTipCount > 0" placement="left-start" class="table-tooltip"
                                    visible-arrow="true" effect="light">
                            <div slot="content" class="code-error-tips">
                                <div v-for="(item,index) in scope.row.codingTip">
                                    {{index+1}}. {{item}}
                                </div>
                            </div>
                            <span class="code-error-span">{{scope.row.codingTipCount}}</span>
                        </el-tooltip>
                        <span v-else>{{scope.row.codingTipCount}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="noneCodingTipCount"
                    label="非编码项缺陷"
                    min-width="110"
                    align="center"
                    sortable="custom"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-tooltip v-if="scope.row.noneCodingTipCount > 0" placement="left-start" class="table-tooltip"
                                    visible-arrow="true" effect="light">
                            <div slot="content" class="not-code-error-tips">
                                <div v-for="(item,index) in scope.row.noneCodingTip">
                                    {{index+1}}. {{item}}
                                </div>
                            </div>
                            <span class="not-code-error-span">{{scope.row.noneCodingTipCount}}</span>
                        </el-tooltip>
                        <span v-else>{{scope.row.noneCodingTipCount}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="nationScore"
                    label="国标得分"
                    min-width="80"
                    align="center"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="status"
                    label="审核状态"
                    min-width="80"
                    align="center"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
            </el-table>
            <pagination v-show="tableData.length > 0" :total="total" :page.sync="currentPage" :limit.sync="pageSize"
                        @pagination="changePage"/>
        </div>
    </div>
</template>

<script>
    import {
        getOverviewList,
        exportList,
        exportWT4,
        exportHQMS,
        exportSJJX
    } from '@/api/medical-records/medical-records-list'
    import {getSortString, dateNumFormat, viewInfoMonth} from '@/utils/filters'
    import exportListNameCode from '@/assets/json/exportListNameCode.json'
    import Pagination from '@/components/Pagination'
    import BtnGroup from '@/components/BtnGroup'
    import FileSaver from 'file-saver'
    import ExcelJS from 'exceljs'

    export default {
        name: 'Dashboard',
        data () {
            return {
                // 搜索条件
                searchForm: {
                    keyword: '',
                    checkState: null,
                    defectSate: 0
                },
                // 显示按钮
                showBtn: ['goBack'],
                // 列表数据
                tableData: [],
                // 排序字段
                sortMap: {},
                // 选中的数据
                multipleSelection: [],
                // 上传数量限制
                limit: 5,
                // 数据总数
                total: 0,
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 20,
                // 表格高度
                tableHeight: 107,
                // 路由参数
                queryForm: {},
                // 排序方式
                sortType: '',
                // 全局搜索内容，用于翻页等不传参时使用数据
                globalForm: {},
                // 使用储存的数据，不去请求
                useStore: false,
                // 错误信息
                errReason: '',
                showDoctor: true,
                showCoder: true,
                // 导出的全部数据
                allexportData: []
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStore = this.$route.query.tags === 'tags'
            let height = document.documentElement.clientHeight - 213 - 10 - 78 - 5 - 32
            this.tableHeight = height > 107 ? height : 107
            this.initPage()
            if (this.$route.name === 'DoctorSummaryAnalysisMRList' || this.$route.name === 'DoctorSummaryMRList') {
                this.showDoctor = true
                this.showCoder = false
            } else if (this.$route.name === 'CoderSummaryAnalysisMRList' || this.$route.name === 'CoderSummaryMRList') {
                this.showDoctor = false
                this.showCoder = true
            }
        },
        mounted () {
            window.onresize = () => {
                // 213=其他元素高度60+50+48+55 10=距离底部边距 78=分页组件高度 5=适应性调整
                let height = document.documentElement.clientHeight - 213 - 10 - 78 - 5 - 32
                this.tableHeight = height > 107 ? height : 107
            }
        },
        methods: {
            viewInfoMonth,
            /**
             * 初始化页面参数
             */
            initPage () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (query) {
                    this.currentPage = query.pageIndex || 1
                    this.pageSize = query.pageSize || 20
                    this.searchForm.checkState = query.checkState
                    this.searchForm.defectSate = query.defectSate || 0
                    this.searchForm.keyword = query.keyword
                    this.errReason = query.errReason
                    this.sortType = query.orderBy
                }
            },
            /**
             * 提交查询
             * @param form 筛选条件
             */
            submitSearch (form) {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                let data = form || this.globalForm
                this.globalForm = data
                let params = {
                    pageSize: this.pageSize,
                    pageIndex: this.currentPage,
                    orderBy: this.sortType,
                    start: data.start,
                    end: data.end,
                    orgId: data.orgId,
                    department: data.department,
                    departmentName: data.departmentName,
                    coder: data.coder,
                    isLast: data.isLast,
                    medicalRecordID: query.medicalRecordID,
                    defectSate: this.searchForm.defectSate,
                    checkState: this.searchForm.checkState,
                    keyword: this.searchForm.keyword,
                    packageID: query.packageID,
                    resident: query.resident
                }
                if (query.errReason) params.errReason = query.errReason
                this.setGetStore(this.$route.name, params)
                if (!params.orderBy) params.orderBy = '`DischargeDate` desc'
                if (this.getSession(this.$route.name, 'getOverviewList') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'getOverviewList')
                    if (res.code.toString() === '200') {
                        this.tableData = res.data.rows
                        this.sortMap = res.data.maps
                        this.total = res.data.total
                    }
                } else {
                    getOverviewList(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {getOverviewList: res})
                        if (res.code.toString() === '200') {
                            this.tableData = res.data.rows
                            this.sortMap = res.data.maps
                            this.total = res.data.total
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            /**
             * 选中事件
             */
            handleSelectionChange (val) {
                this.multipleSelection = val
            },
            /**
             * 导出列表
             */
            toExportList () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (!params.orderBy) params.orderBy = '`DischargeDate` desc'
                if (this.getSelectId()) {
                    params.excelId = this.getSelectId()
                } else {
                    params.excelId = []
                }
                this.$store.dispatch('UpdateLoadingText', '0%')
                this.$store.dispatch('UpdateIsExport', true)
                this.$store.dispatch('UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequest(params)
            },
            /**
             * 发送请求
             * @param params 请求参数
             */
            sendRequest (params) {
                let allIndex = Math.ceil(this.total / 1000)
                exportList(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data.rows)
                        if (params.pageIndex < allIndex) {
                            this.sendRequest({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataList('病案首页列表', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('UpdateIsExport', false)
                        this.$store.dispatch('UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出excel表头
             */
            getHeader () {
                return [{
                    header: '序号', key: 'index', width: 10
                }, {
                    header: '机构名称', key: 'orgName', width: 24
                }, {
                    header: '病案号', key: 'medicalRecordSign', width: 12
                }, {
                    header: '住院次数', key: 'hospitalTime', width: 10
                }, {
                    header: '患者姓名', key: 'patientName', width: 10
                }, {
                    header: '出院科室', key: 'departmentName', width: 16
                }, {
                    header: '出院日期', key: 'dischargeDate', width: 12
                }, {
                    header: '住院医师', key: 'resident', width: 10
                }, {
                    header: '编码员', key: 'coder', width: 10
                }, {
                    header: '主要诊断', key: 'diagnosis', width: 26
                }, {
                    header: '主要手术', key: 'surgery', width: 26
                }, {
                    header: '编码项缺陷', key: 'codingTipCount', width: 40
                }, {
                    header: '非编码项缺陷', key: 'noneCodingTipCount', width: 40
                }, {
                    header: '国标得分', key: 'nationScore', width: 10
                }, {
                    header: '审核状态', key: 'status', width: 10
                }]
            },
            /**
             * 导出列表excel
             */
            exportDataList (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                worksheet.columns = this.getHeader()
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    data[i].diagnosis = `${data[i].diagnosis}\r\n${data[i].diagnosisCode}`
                    data[i].surgery = `${data[i].surgery}\r\n${data[i].surgeryCode}`
                    data[i].codingTipCount = ''
                    data[i].noneCodingTipCount = ''
                    data[i].codingTip.forEach((item, index) => {
                        data[i].codingTipCount += `${index + 1}、${item}`
                        if (index !== data[i].codingTip.length - 1) {
                            data[i].codingTipCount += '\r\n'
                        }
                    })
                    data[i].noneCodingTip.forEach((item, index) => {
                        data[i].noneCodingTipCount += `${index + 1}、${item}`
                        if (index !== data[i].noneCodingTip.length - 1) {
                            data[i].noneCodingTipCount += '\r\n'
                        }
                    })
                    worksheet.addRow(data[i])
                    worksheet.getRow(i + 1).alignment = {vertical: 'middle'}
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('UpdateLoadingText', rate)
                }
                worksheet.getRow(data.length + 1).alignment = {vertical: 'middle'}
                worksheet.getColumn('diagnosis').alignment = {wrapText: true, vertical: 'middle'}
                worksheet.getColumn('surgery').alignment = {wrapText: true, vertical: 'middle'}
                worksheet.getColumn('codingTipCount').alignment = {wrapText: true, vertical: 'middle'}
                worksheet.getColumn('noneCodingTipCount').alignment = {wrapText: true, vertical: 'middle'}
                worksheet.getColumn('index').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('hospitalTime').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('dischargeDate').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('nationScore').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('status').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('UpdateLoadingText', '100%')
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                })
            },
            /**
             * 导出卫统4
             */
            toExportWT4 () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (!params.orderBy) params.orderBy = '`DischargeDate` desc'
                if (this.getSelectId()) {
                    params.excelId = this.getSelectId()
                } else {
                    params.excelId = []
                }
                this.$store.dispatch('UpdateLoadingText', '0%')
                this.$store.dispatch('UpdateIsExport', true)
                this.$store.dispatch('UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequestWT4(params)
            },
            /**
             * 发送请求卫统4
             * @param params 请求参数
             */
            sendRequestWT4 (params) {
                let allIndex = Math.ceil(this.total / 1000)
                exportWT4(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequestWT4({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataListWT4('卫统4', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('UpdateIsExport', false)
                        this.$store.dispatch('UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出WT4列表excel
             */
            exportDataListWT4 (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                let columns = []
                Object.keys(data[0]).forEach(key => {
                    columns.push({
                        header: key.toUpperCase(), key: key, width: 12
                    })
                })
                worksheet.columns = columns
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    worksheet.addRow(data[i])
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('UpdateLoadingText', rate)
                }
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('UpdateLoadingText', '100%')
                    setTimeout(() => {
                        this.$store.dispatch('UpdateIsExport', false)
                        this.$store.dispatch('UpdateLoading', false)
                    })
                })
            },
            /**
             * 导出HQMS标准
             */
            toExportHQMS () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (!params.orderBy) params.orderBy = '`DischargeDate` desc'
                if (this.getSelectId()) {
                    params.excelId = this.getSelectId()
                } else {
                    params.excelId = []
                }
                this.$store.dispatch('UpdateLoadingText', '0%')
                this.$store.dispatch('UpdateIsExport', true)
                this.$store.dispatch('UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequestHQMS(params)
            },
            /**
             * 发送请求HQMS
             * @param params 请求参数
             */
            sendRequestHQMS (params) {
                let allIndex = Math.ceil(this.total / 1000)
                exportHQMS(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequestHQMS({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataListHQMSSJJX('HQMS标准', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('UpdateIsExport', false)
                        this.$store.dispatch('UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 获取HQMS和三级医院表头
             */
            getHQMSHeader (colName) {
                let arr = exportListNameCode[colName]
                let head = []
                Object.keys(arr).forEach(key => {
                    head.push({
                        header: key, key: key.toLowerCase(), width: 12
                    })
                })
                return head
            },
            /**
             * 导出HQMS列表excel
             */
            exportDataListHQMSSJJX (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                worksheet.columns = this.getHQMSHeader(name === 'HQMS标准' ? 'HQMS' : 'SJJX')
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    let obj = {}
                    Object.keys(data[i]).forEach(key => {
                        obj[key.toLowerCase()] = data[i][key]
                        data[i] = {...data[i], ...obj}
                    })
                    worksheet.addRow(data[i])
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('UpdateLoadingText', rate)
                }
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('UpdateLoadingText', '100%')
                    setTimeout(() => {
                        this.$store.dispatch('UpdateIsExport', false)
                        this.$store.dispatch('UpdateLoading', false)
                    })
                })
            },
            /**
             * 导出三级医院标准
             */
            toExportSJJX () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (!params.orderBy) params.orderBy = '`DischargeDate` desc'
                if (this.getSelectId()) {
                    params.excelId = this.getSelectId()
                } else {
                    params.excelId = []
                }
                this.$store.dispatch('UpdateLoadingText', '0%')
                this.$store.dispatch('UpdateIsExport', true)
                this.$store.dispatch('UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequestSJJX(params)
            },

            /**
             * 发送请求三级绩效
             * @param params 请求参数
             */
            sendRequestSJJX (params) {
                let allIndex = Math.ceil(this.total / 1000)
                exportSJJX(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequestSJJX({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataListHQMSSJJX('三级医院绩效标准', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('UpdateIsExport', false)
                        this.$store.dispatch('UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 获取选中id
             */
            getSelectId () {
                let arr = []
                if (this.multipleSelection.length) {
                    this.multipleSelection.forEach(item => {
                        arr.push(item.medicalRecordID)
                    })
                    return arr
                } else {
                    return false
                }
            },
            /**
             * 翻页
             */
            changePage () {
                this.submitSearch()
            },
            /**
             * 排序修改
             * @param colData.prop 排序参数
             * @param colData.order 正序倒序 ascending 升序 descending 降序 null 不排序默认
             */
            sortChange (colData) {
                this.sortType = getSortString(colData, this.sortMap)
                this.tableData = []
                this.currentPage = 1
                this.submitSearch()
            },
            /**
             * 前往病案详情
             * @param row 行数据
             * @param index 索引
             */
            toInfo (row, index) {
                let data = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (viewInfoMonth(row.dischargeDate)) {
                    let params = {
                        ...data,
                        pageIndex: (this.currentPage - 1) * this.pageSize + index + 1,
                        pageSize: 1
                    }
                    let name = ''
                    switch (this.$route.name) {
                    case 'OverviewListIndex':
                        name = 'OverviewListInfo'
                        break
                    case 'ImportMRListIndex':
                        name = 'ImportMRListInfo'
                        break
                    case 'MRListIndex':
                        name = 'MRListInfo'
                        break
                    case 'ScoreListIndex':
                        name = 'ScoreListInfo'
                        break
                    case 'CodingListIndex':
                        name = 'CodingListInfo'
                        break
                    case 'NonCodingListIndex':
                        name = 'NonCodingListInfo'
                        break
                    case 'DepSummaryMRList':
                        name = 'DepSummaryMRInfo'
                        break
                    case 'DepSummaryAnalysisMRList':
                        name = 'DepSummaryAnalysisMRInfo'
                        break
                    case 'DoctorSummaryMRList':
                        name = 'DoctorSummaryInfo'
                        break
                    case 'DoctorSummaryAnalysisMRList':
                        name = 'DoctorSummaryAnalysisMRInfo'
                        break
                    case 'CoderSummaryMRList':
                        name = 'CoderSummaryMRInfo'
                        break
                    case 'CoderSummaryAnalysisMRList':
                        name = 'CoderSummaryAnalysisMRInfo'
                        break
                    case 'QCEffectMRList':
                        name = 'QCEffectMRInfo'
                        break
                    }
                    this.$store.dispatch('search/coverSearchFormItem', {
                        pageName: name,
                        query: params
                    })
                    this.$router.push({name: name})
                }
            }
        },
        components: {
            BtnGroup,
            Pagination
        },
        filters: {
            getStatus (val) {
                switch (val) {
                case 0:
                    return '未审核'
                case 1:
                    return '已审核'
                case 2:
                    return '驳回'
                }
            },
            dateNumFormat
        },
        beforeDestroy () {
            window.onresize = null
        }
    }
</script>

<style lang="scss" scoped>
    .medical-records-list-container {
        /deep/ .el-form-item {
            margin-bottom: 0;

        }
        .status-input {
            width: 90px;
        }
        .defectSate-input {
            width: 120px;
            /deep/ .el-input__inner {
                padding: 0 10px 0 5px;
            }
        }
        .keyword-input {
            width: 150px;
            /deep/ .el-input__inner {
                padding: 0 5px 0 5px;
            }
        }
        .table-box {
            height: calc(100vh - 215px + 30px);
            background: #fff;
            padding: 0 10px;
            .head {
                height: 48px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                h3 {
                    font-size: 16px;
                    color: #000;
                    font-weight: 600;
                    line-height: 48px;
                    span {
                        font-size: 12px;
                        color: #7e7e7e;
                        font-weight: normal;
                        margin-left: 20px;
                    }
                }
                .btn-box {
                    display: flex;
                    justify-content: flex-end;
                    align-items: center;
                }
            }
            .data-table {
                width: 100%;
            }
        }
    }
</style>
